<template>
  <v-app id="dashboard">
    <v-navigation-drawer app width="240" value="true">
      <v-list subheader dense>
        <v-list-item class="py-0">
          <div class="title-combo">
            <img :src="titleLeftUrl" alt="title-left" height="64" />
            <img :src="titleRightUrl" alt="title-right" height="64" />
          </div>
        </v-list-item>

        <v-divider class="my-2" />

        <v-list-item :input-value="$route.path === '/main'" @click="goToDashboard">
          <v-list-item-icon><v-icon color="primary">mdi-view-dashboard</v-icon></v-list-item-icon>
          <v-list-item-title>Dashboard</v-list-item-title>
        </v-list-item>

        <v-list-group v-model="isSystemOpen" prepend-icon="mdi-cog-outline" class="primary-menu-group">
          <template v-slot:activator>
            <v-list-item-content>
              <v-list-item-title class="primary-menu-title">System Management</v-list-item-title>
            </v-list-item-content>
          </template>

          <v-list-item :input-value="$route.path.startsWith('/main/user')" @click="goTo('user')" class="secondary-menu-item">
            <v-list-item-icon><v-icon size="18">mdi-account-multiple-outline</v-icon></v-list-item-icon>
            <v-list-item-title class="secondary-menu-title">User Management</v-list-item-title>
          </v-list-item>
          <v-list-item :input-value="$route.path.startsWith('/main/role')" @click="goTo('role')" class="secondary-menu-item">
            <v-list-item-icon><v-icon size="18">mdi-shield-account-outline</v-icon></v-list-item-icon>
            <v-list-item-title class="secondary-menu-title">Role Management</v-list-item-title>
          </v-list-item>
          <v-list-item :input-value="$route.path.startsWith('/main/permission')" @click="goTo('permission')" class="secondary-menu-item">
            <v-list-item-icon><v-icon size="18">mdi-lock-check-outline</v-icon></v-list-item-icon>
            <v-list-item-title class="secondary-menu-title">Permission Management</v-list-item-title>
          </v-list-item>
          <v-list-item :input-value="$route.path.startsWith('/main/fixed-response')" @click="goTo('fixed-response')" class="secondary-menu-item">
            <v-list-item-icon><v-icon size="18">mdi-api</v-icon></v-list-item-icon>
            <v-list-item-title class="secondary-menu-title">Fixed Response Management</v-list-item-title>
          </v-list-item>
        </v-list-group>

        <v-list-group v-model="isSinuIntelOpen" prepend-icon="mdi-brain" class="primary-menu-group">
          <template v-slot:activator>
            <v-list-item-content>
              <v-list-item-title class="primary-menu-title">SinuIntel</v-list-item-title>
            </v-list-item-content>
          </template>

          <v-list-item :input-value="$route.path.startsWith('/main/simulation')" @click="goTo('simulation')" class="secondary-menu-item">
            <v-list-item-icon><v-icon size="18">mdi-cog-outline</v-icon></v-list-item-icon>
            <v-list-item-title class="secondary-menu-title">Generator Unit</v-list-item-title>
          </v-list-item>
          <v-list-item :input-value="$route.path.startsWith('/main/power-canvas')" @click="goTo('power-canvas')" class="secondary-menu-item">
            <v-list-item-icon><v-icon size="18">mdi-transmission-tower</v-icon></v-list-item-icon>
            <v-list-item-title class="secondary-menu-title">Power Grid Topology</v-list-item-title>
          </v-list-item>
        </v-list-group>
      </v-list>
    </v-navigation-drawer>

    <v-app-bar app color="white" elevation="1">
      <v-breadcrumbs :items="breadcrumbs" divider="/" class="ml-2">
        <template v-slot:item="{ item }">
          <v-breadcrumbs-item :disabled="item.disabled" :to="item.to" :href="item.href" exact>
            {{ item.text }}
          </v-breadcrumbs-item>
        </template>
      </v-breadcrumbs>
      <v-spacer />
      <div class="mr-2 grey--text">Welcome, Admin</div>
      <v-menu offset-y>
        <template v-slot:activator="{ on, attrs }">
          <v-avatar size="28" color="primary" v-bind="attrs" v-on="on">
            <span class="white--text text-caption font-weight-bold">A</span>
          </v-avatar>
        </template>
        <v-list dense>
          <v-list-item @click="openChangePasswordDialog">
            <v-list-item-icon><v-icon>mdi-lock-reset</v-icon></v-list-item-icon>
            <v-list-item-title>Change Password</v-list-item-title>
          </v-list-item>
          <v-list-item @click="onLogout">
            <v-list-item-icon><v-icon>mdi-logout</v-icon></v-list-item-icon>
            <v-list-item-title>Logout</v-list-item-title>
          </v-list-item>
        </v-list>
      </v-menu>
    </v-app-bar>

    <v-main>
      <v-container fluid>
        <router-view v-if="$route.path !== '/main'" />

        <div v-else>
          <div class="text-h6 font-weight-bold mb-3">System Modules</div>
			<v-row align="stretch">
				<v-col v-for="m in sortedModules" :key="m.key" cols="12" sm="6" md="4" lg="3" xl="2" class="d-flex">
					<v-card outlined class="d-flex flex-column w-100 module-card" :class="{ 'disabled-card': !m.enabled, 'sim-click': m.key==='sim' || m.key==='power' }" @click="onModuleClick(m)">
                <v-sheet height="4" :style="{ background: 'linear-gradient(90deg, #5C8F5A, #5E8197)'}" />
                <v-card-text class="d-flex flex-grow-1">
                  <v-avatar :color="undefined" size="44" class="mr-3" :style="{ background: m.bg }">
                    <span v-html="m.icon" />
                  </v-avatar>
                  <div>
                    <div class="subtitle-1 font-weight-bold">{{ m.name }}</div>
                    <div class="caption grey--text text--darken-1">{{ m.desc }}</div>
                  </div>
                </v-card-text>
              </v-card>
            </v-col>
          </v-row>
        </div>
      </v-container>
    </v-main>
    
    <v-dialog v-model="changePasswordDialog" max-width="420">
      <v-card>
        <v-card-title class="headline">Change Password</v-card-title>
        <v-card-text>
          <v-form ref="changePwdFormRef" v-model="changePwdFormValid" lazy-validation>
            <v-text-field
              v-model="changePwdForm.currentPassword"
              :append-icon="showCurrentPwd ? 'mdi-eye-off' : 'mdi-eye'"
              :type="showCurrentPwd ? 'text' : 'password'"
              @click:append="showCurrentPwd = !showCurrentPwd"
              label="Current Password"
              dense
              outlined
              :rules="[rules.required]"
            />
            <v-text-field
              v-model="changePwdForm.newPassword"
              :append-icon="showNewPwd ? 'mdi-eye-off' : 'mdi-eye'"
              :type="showNewPwd ? 'text' : 'password'"
              @click:append="showNewPwd = !showNewPwd"
              label="New Password"
              dense
              outlined
              :rules="[rules.required, rules.min6, rules.notSameAsOld]"
            />
            <v-text-field
              v-model="changePwdForm.confirmPassword"
              :append-icon="showConfirmPwd ? 'mdi-eye-off' : 'mdi-eye'"
              :type="showConfirmPwd ? 'text' : 'password'"
              @click:append="showConfirmPwd = !showConfirmPwd"
              label="Confirm New Password"
              dense
              outlined
              :rules="[rules.required, rules.confirmMatch]"
            />
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="closeChangePasswordDialog" :disabled="submittingChangePwd">Cancel</v-btn>
          <v-btn color="primary" @click="submitChangePassword" :loading="submittingChangePwd">Confirm</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-snackbar v-model="snackbar.show" :color="snackbar.color" timeout="3000">
      {{ snackbar.message }}
    </v-snackbar>
    
  </v-app>
</template>

<script>
import titleLeftPng from '@/assets/title_left.png'
import titleRightPng from '@/assets/title_right.png'
export default {
  name: 'MainDashboard',
  data() {
    return {
      titleLeftUrl: titleLeftPng,
      titleRightUrl: titleRightPng,
      isSystemOpen: true,
      isSinuIntelOpen: true,
      modules: [
        {
          key: 'hub',
          name: 'Data Hub',
          desc: 'Centralized data management platform for collection, storage, processing and analytics',
          bg: 'var(--brand-energy)',
          enabled: false,
          icon: `<svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 3L3 7.5V12c0 5 9 9 9 9s9-4 9-9V7.5L12 3z" stroke="white" stroke-width="1.6" fill="none"/></svg>`
        },
        {
          key: 'twin',
          name: 'Digital Twin',
          desc: 'Real-time mapping and interaction between physical and digital worlds',
          bg: 'var(--brand-energy)',
          enabled: false,
          icon: `<svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7 7h10v10H7z" stroke="white" stroke-width="1.6"/><path d="M7 12h10" stroke="white" stroke-width="1.6"/></svg>`
        },
        {
          key: 'agent',
          name: 'AI Agent',
          desc: 'Intelligent agent system with autonomous decision-making and task execution',
          bg: 'var(--brand-energy)',
          enabled: true,
          icon: `<svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="8" r="3.5" stroke="white" stroke-width="1.6"/><path d="M5 19a7 7 0 0 1 14 0" stroke="white" stroke-width="1.6"/></svg>`
        },
        {
          key: 'dash',
          name: 'Dashboard',
          desc: 'Visual dashboard for real-time monitoring and business insights',
          bg: 'var(--brand-energy)',
          enabled: false,
          icon: `<svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 13h4v7H4zM10 4h4v16h-4zM16 9h4v11h-4z" fill="white"/></svg>`
        },
        {
          key: 'map',
          name: 'Map',
          desc: 'Pick coordinates in Abu Dhabi and place markers',
          bg: 'var(--brand-energy)',
          enabled: true,
          icon: `<svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C8.686 2 6 4.686 6 8c0 4.5 6 12 6 12s6-7.5 6-12c0-3.314-2.686-6-6-6zm0 8.5A2.5 2.5 0 1 1 12 5.5a2.5 2.5 0 0 1 0 5z" fill="white"/></svg>`,
          subPages: [
            { key: 'map', name: 'Time Series', desc: 'Solar energy time series analysis' },
            { key: 'heatmap', name: 'Annual Heatmap', desc: 'Yearly solar energy output heatmap' }
          ]
        },
        {
          key: 'voice',
          name: 'Voice Test',
          desc: 'Test voice recognition and real-time speech-to-text functionality',
          bg: 'var(--brand-energy)',
          enabled: true,
          icon: `<svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z" fill="white"/><path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z" fill="white"/></svg>`
        }
      ],
      stats: [
        { key: 'users', value: '256', label: 'Active Users', bg: 'var(--brand-energy)', icon: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 12a5 5 0 1 0 0-10 5 5 0 0 0 0 10zM4 21a8 8 0 0 1 16 0v1H4v-1z" fill="white"/></svg>` },
        { key: 'mods', value: '5', label: 'System Modules', bg: 'var(--brand-energy)', icon: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect x="4" y="4" width="6" height="6" rx="1.2" fill="white"/><rect x="14" y="4" width="6" height="6" rx="1.2" fill="white"/><rect x="4" y="14" width="6" height="6" rx="1.2" fill="white"/><rect x="14" y="14" width="6" height="6" rx="1.2" fill="white"/></svg>` },
        { key: 'gb', value: '1,024', label: 'GB/Day Processing', bg: 'var(--brand-energy)', icon: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 12h16M4 12c4-6 12-6 16 0" stroke="white" stroke-width="1.6"/></svg>` },
        { key: 'uptime', value: '99.9%', label: 'System Uptime', bg: 'var(--brand-energy)', icon: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M20 6L9 17l-5-5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>` }
      ]
      ,
      changePasswordDialog: false,
      changePwdFormValid: false,
      changePwdForm: { currentPassword: '', newPassword: '', confirmPassword: '' },
      showCurrentPwd: false,
      showNewPwd: false,
      showConfirmPwd: false,
      submittingChangePwd: false,
      snackbar: { show: false, message: '', color: 'success' },
      rules: {
        required: v => !!v || 'Required',
        min6: v => (v && v.length >= 6) || 'At least 6 characters',
        notSameAsOld: v => (v !== this.changePwdForm.currentPassword) || 'New password must differ',
        confirmMatch: v => (v === this.changePwdForm.newPassword) || 'Passwords do not match'
      }
    }
  },
  computed: {
    breadcrumbs() {
      const second = this.$route.name === 'main' ? 'Dashboard' : ((this.$route.meta && this.$route.meta.title) || '')
      return [
        { text: 'Home', to: '/main' },
        { text: second, disabled: true }
      ]
    },
    sortedModules() {
      const order = ['map', 'agent', 'voice']
      const withRank = this.modules.map((m, idx) => ({ ...m, _rank: order.includes(m.key) ? order.indexOf(m.key) : (100 + idx) }))
      return withRank.sort((a, b) => a._rank - b._rank)
    }
  },
  methods: {
    goToDashboard() { this.$router.push('/main') },
    goTo(name) { this.$router.push(`/main/${name}`) },
    onModuleClick(m) {
      if (!m || m.enabled === false) return
      if (m.key === 'map') {
        // Navigate to map page with tabs for sub-features
        this.goTo('map')
        return
      }
      if (m.key === 'voice') return this.goTo('voice-test')
      if (m.key === 'agent') {
        if (typeof window !== 'undefined') {
          window.open('https://47.84.193.125:30014/aiagent/#/login', '_blank')
        }
        return
      }
    },
    openChangePasswordDialog() {
      this.changePasswordDialog = true
    },
    closeChangePasswordDialog() {
      this.changePasswordDialog = false
      if (this.$refs.changePwdFormRef) {
        this.$refs.changePwdFormRef.resetValidation()
      }
      this.changePwdForm = { currentPassword: '', newPassword: '', confirmPassword: '' }
      this.showCurrentPwd = false
      this.showNewPwd = false
      this.showConfirmPwd = false
    },
    async submitChangePassword() {
      const form = this.$refs.changePwdFormRef
      if (form && !form.validate()) return
      this.submittingChangePwd = true
      try {
        await this.$api.account.changePassword({
          currentPassword: this.changePwdForm.currentPassword,
          newPassword: this.changePwdForm.newPassword
        })
        this.snackbar = { show: true, message: 'Password updated successfully', color: 'success' }
        this.closeChangePasswordDialog()
      } catch (e) {
        const msg = (e && e.response && e.response.data && (e.response.data.message || e.response.data.error)) || 'Failed to update password'
        this.snackbar = { show: true, message: msg, color: 'error' }
      } finally {
        this.submittingChangePwd = false
      }
    },
    onLogout() {
      if (typeof window !== 'undefined' && window.localStorage) {
        window.localStorage.removeItem('token')
      }
      this.$router.replace('/login')
    }
  }
}
</script>

<style scoped>
#dashboard { background: #f6f7fb; }
.module-card { min-height: 120px; }
.disabled-card { filter: grayscale(0.6); opacity: 0.5; pointer-events: none; }
.title-combo { display: flex; align-items: center; gap: 4px; padding: 0; height: 64px; }
.title-combo img { height: 64px; width: auto; display: block; }

/* 一级菜单样式 */
.primary-menu-group {
  margin: 4px 0;
}

.primary-menu-group .v-list-item__content {
  padding: 8px 0;
}

.primary-menu-title {
  font-weight: 600 !important;
  font-size: 14px !important;
  color: #333 !important;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.primary-menu-group .v-list-item__icon {
  margin-right: 12px !important;
}

.primary-menu-group .v-list-item__icon .v-icon {
  color: #666 !important;
  font-size: 20px !important;
}

/* 二级菜单样式 */
.secondary-menu-item {
  margin-left: 16px !important;
  margin-right: 8px !important;
  margin-bottom: 2px !important;
  border-radius: 6px !important;
  min-height: 36px !important;
}

.secondary-menu-item .v-list-item__content {
  padding: 6px 0 !important;
}

.secondary-menu-title {
  font-weight: 400 !important;
  font-size: 13px !important;
  color: #666 !important;
}

.secondary-menu-item .v-list-item__icon {
  margin-right: 8px !important;
  margin-left: 8px !important;
}

.secondary-menu-item .v-list-item__icon .v-icon {
  color: #666 !important;
  font-size: 16px !important;
}

/* 二级菜单悬停效果 */
.secondary-menu-item:hover {
  background-color: #f5f5f5 !important;
}

.secondary-menu-item:hover .secondary-menu-title {
  color: #333 !important;
}

.secondary-menu-item:hover .v-list-item__icon .v-icon {
  color: #333 !important;
}

/* 二级菜单激活状态 */
.secondary-menu-item.v-list-item--active {
  background-color: #e8f5e8 !important;
}

.secondary-menu-item.v-list-item--active .secondary-menu-title {
  color: #5C8F5A !important;
  font-weight: 500 !important;
}

.secondary-menu-item.v-list-item--active .v-list-item__icon .v-icon {
  color: #5C8F5A !important;
}

/* 菜单组展开/收起动画 */
.primary-menu-group .v-list-group__items {
  padding-left: 0 !important;
}

/* 一级菜单悬停效果 */
.primary-menu-group .v-list-item:hover {
  background-color: #f8f9fa !important;
}

.primary-menu-group .v-list-item:hover .primary-menu-title {
  color: #333 !important;
}

.primary-menu-group .v-list-item:hover .v-list-item__icon .v-icon {
  color: #333 !important;
}

/* 一级菜单激活状态（当子菜单被选中时） */
.primary-menu-group.v-list-group--active .primary-menu-title {
  color: #5C8F5A !important;
}

.primary-menu-group.v-list-group--active .v-list-item__icon .v-icon {
  color: #5C8F5A !important;
}
</style>


